<template>
  <el-dialog v-model="drawer" :title="isEdit ? '编辑供应商' : '新建供应商'" :append-to-body="true" width="670px" custom-class="SupplierCreate" @close="close">
    <el-form :model="form" :rules="rules" size="small" ref="ruleFormRef" label-width="110px" class="drawer-form">
      <el-form-item label="供应商图片:" prop="supplierImg">
        <el-upload ref="uploadBanner" :action="uploadUrl" :headers="headers" @change="changeSupplierImg"
                   list-type="picture-card" :auto-upload="false" :multiple="false" :limit="1" style="margin-bottom: 10px;">
          <el-icon>
            <ele-Camera />
          </el-icon>
          <template #file="{ file }">
            <img class="el-upload-list__item-thumbnail" :src="file.url" />
            <span class="el-upload-list__item-actions">
										<span class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview(file)">
											<el-icon>
												<ele-ZoomIn />
											</el-icon>
										</span>
										<span class="el-upload-list__item-delete" @click="handleRemove(file)">
											<el-icon>
												<ele-Delete />
											</el-icon>
										</span>
									</span>
          </template>
        </el-upload>
        <div class="auto">
          <el-button>自动填充</el-button>
        </div>
        <div class="hand-movement" style="display: block;">
          <el-button style="width: 250px;">手动录入</el-button>
        </div>
      </el-form-item>

      <el-divider content-position="left">供应商基础信息</el-divider>

      <el-row>
        <el-form-item label="供应商全称:" prop="name" >
          <el-input v-model="form.name" placeholder="全称" style="width: 250px;"/>
        </el-form-item>
        <el-form-item label="创建日期:" prop="createTime">
          <el-date-picker style="width:125px;" v-model="form.createTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date" placeholder="请选择日期" size="small"/>
        </el-form-item>
      </el-row>

      <el-form-item label="供应商简称:" prop="shortName" >
        <el-input v-model="form.shortName" placeholder="简称" maxlength="4" style="width: 250px;"></el-input>
      </el-form-item>

      <el-form-item label="供应产品:" prop="productName" >
        <el-select-v2
            v-model="form.productName"
            :options="offerProductOption"
            placeholder="请选择供应产品"
            size="small"
            style="width:250px;"
            allow-create
            filterable
            clearable>
          <template #default="{ item,index }">
            <span style="float: left">{{ item.label }}</span>
            <el-button type="danger" text :icon="Delete" style="float: right;height: 34px" @click.stop="delOfferOption(item,index)"/>
          </template>
        </el-select-v2>
      </el-form-item>

      <el-form-item label="采购人:" prop="purchaseUserId" >
        <el-select v-model="form.purchaseUserId" placeholder="请选择采购人" style="width:160px">
            <el-option v-for="item in purchaserOption" :key="item.userId" :label="item.nickname" :value="item.userId"></el-option>
        </el-select>
      </el-form-item>

      <el-row>
        <el-form-item label="供应商阶段:" prop="stage" >
          <el-select v-model="form.stage" placeholder="请选择供应商阶段" style="width:160px">
            <el-option v-for="item in stageOption" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商状态:" prop="state" >
          <el-select v-model="form.state" placeholder="请选择供应商状态" style="width:160px">
            <el-option v-for="item in stateOption" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-row>


      <div v-for="(item, index) in form.contacts" :key="item.id" style="margin-bottom:10px;">
        <el-row class="row-item">
          <div>
            <el-form-item prop="contactName" :label="`联系人${index + 1}`">
              <el-input placeholder="请输入联系人" v-model="item.name"></el-input>
            </el-form-item>
            <el-form-item prop="roleName" label="角色" style="margin-top: -10px;">
              <el-select-v2
                  v-model="item.roleName"
                  :options="rolesList"
                  placeholder="请选择联系人角色"
                  size="small"
                  style="width:160px;"
                  allow-create
                  filterable
                  clearable>
              </el-select-v2>
            </el-form-item>
          </div>
          <div>
            <el-form-item prop="position" label="职位">
              <el-select-v2
                  v-model="item.position"
                  @change="selectRoleEvent"
                  :options="positionList"
                  placeholder="请选择联系人职位"
                  size="small"
                  style="width:160px;"
                  allow-create
                  filterable
                  clearable>
              </el-select-v2>
            </el-form-item>
            <el-form-item prop="contactPhone" label="联系电话" style="width:270px;margin-top:-10px">
              <el-input placeholder="请输入联系电话" :maxlength="11" :minlength="11" @blur="checkContactPhone(item)" v-model="item.phone"></el-input>
              <el-checkbox v-model="item.wechat" label="wei" size="small" :true-label="1" :false-label="0" style="margin-right: 10px;">微信同号</el-checkbox>
              <el-checkbox v-model="item.type" label="wei" @change="onIsMainEvent(item)" size="small" :true-label="1" :false-label="0">主要联系人</el-checkbox>
            </el-form-item>
          </div>
        </el-row>
        <el-row style="margin-left:110px;margin-top: -18px" v-if="(form.contacts.length == 1 || (form.contacts.length > 1 && index > 0))">
          <el-icon :size="16" v-if="(index === form.contacts.length - 1)" color="var(--el-color-primary)" style="margin-right:5px;margin-left:5px;cursor:pointer;margin-top:4px;" @click="addContact">
            <ele-CirclePlus/>
          </el-icon>
          <el-icon :size="16" color="var(--el-color-danger)" style="margin-right:5px;margin-left:5px;cursor:pointer;margin-top:4px;" v-if="index > 0" @click="delContact(index)">
            <ele-Remove/>
          </el-icon>
        </el-row>
      </div>


      <div v-for="(item, index) in form.portraitLabels" :key="item.id" style="margin-bottom:10px;">
        <el-row class="row-item">
          <div>
            <el-form-item prop="portraitLabel" :label="`画像标签${index + 1}`">
              <el-input v-model="item[index]" :placeholder="`画像标签${index+1}`" style="width: 250px;"></el-input>
            </el-form-item>
          </div>
        </el-row>
        <el-row style="margin-left:110px;margin-top: 5px" v-if="(form.portraitLabels.length == 1 || (form.portraitLabels.length > 1 && index > 0))">
          <el-icon :size="16" v-if="(index === form.portraitLabels.length - 1)" color="var(--el-color-primary)" style="margin-right:5px;margin-left:5px;cursor:pointer;margin-top:4px;" @click="addPortrait">
            <ele-CirclePlus/>
          </el-icon>
          <el-icon :size="16" color="var(--el-color-danger)" style="margin-right:5px;margin-left:5px;cursor:pointer;margin-top:4px;" v-if="index > 0" @click="delPortrait(index)">
            <ele-Remove/>
          </el-icon>
        </el-row>
      </div>

      <el-form-item label="供应商来源:" prop="source" >
<!--        <el-input v-model="form.source" placeholder="供应商来源" style="width: 250px;"></el-input>-->
        <el-select-v2
            v-model="form.source"
            :options="SupplierSourceList"
            placeholder="请选择供应商来源"
            size="small"
            style="width:160px;"
            allow-create
            filterable
            clearable
        >
        </el-select-v2>
      </el-form-item>

      <el-form-item label="供应商附件" prop="lineFile">
        <el-upload class="upload-demo" drag :action="action" :multiple="false" :auto-upload="false" :headers="headers" @change="changeSupplierFile">
          <el-icon class="el-icon--upload">
            <ele-UploadFilled/>
          </el-icon>
          <div class="el-upload__text">
            拖拽上传或 <em>点击上传</em>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="地点定位" prop="location">
        <el-cascader ref="areaTree" v-model="form.addrName" :options="citys" :props="props" style="width:89.8%" @change="handleChange"/>
        <el-input placeholder="请输入详细地址" v-model="form.address" style="width:89.8%;margin-top:10px;" @blur="getMarket"></el-input>
        <!--  地图  -->
        <div id="map" ref="map"></div>
      </el-form-item>
      <el-form-item prop="remark" label="备注" class="remark-item">
        <el-input type="textarea" v-model="form.remark"></el-input>
      </el-form-item>
    </el-form>
    <el-row class="footer-fixed">
      <el-button type="primary" size="small" @click="submit(ruleFormRef)">提交</el-button>
      <el-button size="small" @click="cancel(ruleFormRef)">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script setup>
import { reactive, toRefs ,ref,computed,shallowRef,watch, getCurrentInstance } from 'vue'
import { Session } from '/@/utils/storage'
import {city} from '/@/utils/city'
import {ElMessage} from "element-plus";
import AMapLoader from '@amap/amap-jsapi-loader';
import {changeDetSelect} from '/@/utils/utils'
import supplierApi from '/@/api/supplier/index'
import purchaseOrderApi from '/@/api/supplier/purchaseOrder'
import { formatDate } from '/@/utils/formatTime'
import Cookies from "js-cookie";
import {getEnterpriseUsers} from '/@/api/sys/user';
import {Delete} from '@element-plus/icons-vue'
import {delProductRecord} from "../../../api/supplier";

let rules = {
  //supplierImg:[{required: true, trigger: 'blur', message: '请上传证件'}],
  name: [{required: true, trigger: 'blur', message: '请输入供应商全称'}],
  shortName: [{ required: true, trigger: 'blur', message: '请输入供应商简称'}],
  productName:[{ required: true, trigger: 'blur', message: '请输入供应产品'}],
  stage:[{ required: true, trigger: 'blur', message: '请选择供应商阶段'}],
  state:[{ required: true, trigger: 'blur', message: '请选择供应商状态'}],
  // location:[{ required: true, trigger: 'blur', message: '请输入地址'}]
}
let positionList = [{label:"总经理",value:"总经理"},{label:"市场负责人",value:"市场负责人"},{label:"招商部负责人",value:"招商部负责人"},{label:"研发部工程师",value:"研发部工程师"},{label:"采购部负责人",value:"采购部负责人"}]
let rolesList = [{label:"决策人",value:"决策人"},{label:"执行人",value:"执行人"},{label:"联络人",value:"联络人"},{label:"协助人",value:"协助人"},{label:"其他",value:"其他"}]
let stageOption = [{label:"线索",value:"0"},{label:"需求沟通",value:"1"},{label:"报价",value:"2"},{label:"合同订单",value:"3"}]
let stateOption = [{label:"合作",value:"0"},{label:"终止",value:"1"},{label:"沟通",value:"2"}]
let uploadUrl = ''
let action = '#'

let map = shallowRef(null);
let marker = shallowRef(null);
let citys = city

const {proxy} = getCurrentInstance()
let geocoder = null
let Map = null
let dialogBannerVisible = ref(false)
const ruleFormRef = ref()
let dialogImageUrl = ref('')
let addrName = ref('')
const uploadBanner = ref()
let purchaserOption = ref([])
let fileList = ref([])
let SupplierSourceList = ref([])
let supplierImg = ref(null)
let offerProductOption = ref([])
let props = reactive({
  expandTrigger: 'hover',
  value: 'code'
})


const props2 = defineProps({
  isEdit: {
    props: Boolean,
    default: false
  },
  dialogDrawer: {
    props: Boolean,
    default: false
  },
  SupplierSource: {
    type: Array,
    default() {
      return {}
    }
  },
})
const emit = defineEmits(['isEdit','update:dialogDrawer','onSubmit'])
const { isEdit , dialogDrawer , SupplierSource } = toRefs(props2)
let drawer = computed({
  get: () => {
    if (dialogDrawer.value){
      getEnterpriseUsers().then(res => {
        purchaserOption.value = res.data
        form.purchaseUserId = Cookies.get('userId')
      })

      purchaseOrderApi.getHistoryProducts().then(res => {
        offerProductOption.value = []
        for (let i = 0; i < res.data.length; i++) {
          offerProductOption.value.push({
            label:res.data[i].name,
            value:i,
            id:res.data[i].id
          })
        }
      })

      SupplierSourceList.value= []
      for (let i = 0; i < SupplierSource.value.length; i++) {
        SupplierSourceList.value.push({
          label:SupplierSource.value[i].name,
          value:SupplierSource.value[i].value
        })
      }

      form.createTime = formatDate(new Date, 'YYYY-mm-dd HH:MM:SS')

    }
    return dialogDrawer.value
  },
  set: val => {
    emit('update:dialogDrawer', val)
  }
})
const headers = ref({
  '17work': Session.get('token')
})
let form = reactive({
  name:'', // 全称
  shortName:'', //简称
  productName:'', //产品名称
  purchaseUserId:'',//采购人用户ID
  stage:'',
  createTime:'',
  state:'',
  areaDetail:[],
  contacts: [{index:0,name: '', phone: '', wechat: 0, type: 1, position: '',roleName:''}], //联系人列表
  mainContact :{name: '', phone: '', wechat: 0, type: 1, position: '',roleName:''},  //主要联系人
  portraitLabels:[""], //用户画像 暂时无功能
  source:'2', //默认为2 其他
  address: null,  // 地址全称
  addrCode: null,   // 省市区地址编码, 逗号隔开
  addrName: null,   // 省市区地址, 逗号隔开
  lng: null,    // 经度
  lat: null,    // 纬度
  remark:''
})
const changeSupplierFile = (file,fileList) => {
  fileList.value = fileList
}
//供应商图片数据
const changeSupplierImg = (file) => {
  supplierImg.value = file.raw
}
//关闭时触发
const close = () => {
  emit('update:dialogDrawer', false)
}
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogBannerVisible = true
}
//删除图片回调
const handleRemove = file => {
  uploadBanner.value.handleRemove(file)
}
const selectRoleEvent = (e) => {

}
watch(() => dialogDrawer.value, val => {
  emit("update:dialogDrawer", val)
  if (val) {
    // 初始化
    initMap()
  } else {
    // 销毁
    // map && map.destroy()
  }
})
const initMap = () => {
  AMapLoader.load({
    key: "54258384f8ac03ec2032977d0a45e678",             // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Geolocation', 'AMap.LngLat', 'AMap.Marker', 'AMap.Pixel', 'AMap.Geocoder'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    Map = AMap
    map = new AMap.Map("map", {  //设置地图容器id
      zoom: 16
    })
    let geolocation = new AMap.Geolocation({
      // 是否使用高精度定位，默认：true
      enableHighAccuracy: true,
      // 设置定位超时时间，默认：无穷大
      timeout: 10000,
    })
    geolocation.getCityInfo((status, result) => {
      if (status == 'complete') {
        // eslint-disable-next-line vue/no-ref-as-operand
        map.setCenter(new AMap.LngLat(result.position[0], result.position[1]))
        marker = new AMap.Marker({
          icon: "/src/assets/position.png",
          position: result.position,
          offset: new AMap.Pixel(-13, -30)
        });
        // eslint-disable-next-line vue/no-ref-as-operand
        marker.setMap(map);
      } else {
        // eslint-disable-next-line vue/no-ref-as-operand
        map.setCenter(new AMap.LngLat(113.295799, 23.035493))
        marker = new AMap.Marker({
          icon: "/src/assets/position.png",
          position: [113.295799, 23.035493],
          offset: new AMap.Pixel(-13, -30)
        });
        // eslint-disable-next-line no-console
        console.log('error => ', result)
      }
    })
    geocoder = new AMap.Geocoder()
    // eslint-disable-next-line vue/no-ref-as-operand
    map.on('click', (result) => {
      const lng = result.lnglat.getLng()
      const lat = result.lnglat.getLat()
      // eslint-disable-next-line vue/no-ref-as-operand
      marker.setPosition(new AMap.LngLat(lng, lat))
      geocoder.getAddress([lng, lat], function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          // result为对应的地理位置详细信息
          console.log("地图回调数据=>", result);
          const addressComponent = result.regeocode.addressComponent
          const {district, city, province} = addressComponent;
          const codeArray = changeDetSelect(addressComponent.adcode, citys, 'code')
          // 省
          // form['province'] = province;
          // form['provincecode'] = codeArray[0]
          // // 市
          // form['city'] = city;
          // form['citycode'] = codeArray[1]
          // //  区/县
          // form['district'] = district
          // form['adcode'] = codeArray[2]
          // 地址全称
          addrName.value = province + ',' + city + ',' + district
          form.addrName = codeArray
          form.addrCode = codeArray[0] + ',' + codeArray[1] + ',' + codeArray[2]
          form.address = result.regeocode.formattedAddress
          form.lng = lng
          form.lat = lat
        }
      })
    });
  }).catch(e => {
    // eslint-disable-next-line no-console
    console.log(e);
  })
}
// 点击选择地址
const handleChange = async () => {
  console.log(proxy.$refs['areaTree'].getCheckedNodes())
  form.areaDetail = proxy.$refs['areaTree'].getCheckedNodes()[0].pathLabels
  // 选择地址后激活信息地址框
}
const getMarket = () => {
  geocoder.getLocation(form.areaDetail.join('') + form.address, function (status, result) {
    if (status === 'complete' && result.info === 'OK') {
      // eslint-disable-next-line vue/no-ref-as-operand
      map.setCenter(new Map.LngLat(result.geocodes[0].location.lng, result.geocodes[0].location.lat))
      // eslint-disable-next-line vue/no-ref-as-operand
      marker.setPosition(new Map.LngLat(result.geocodes[0].location.lng, result.geocodes[0].location.lat))
    }
  })
}
// 检查是否是手机号
const checkContactPhone = (e) => {
  if (!e) return false
  if (!e.phone) return false;
  const testMobileValue = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
  if (testMobileValue.test(e.phone))
    return true;
  ElMessage.error("请输入正确的手机号")
  return false
}
// 点击设置为空主要联系人
const onIsMainEvent = (e) => {
  // 检查是不是当前为空默认联系人，然后点击取消不为联系人，但是当前数组上没有默认联系人情况下
  // 对当前取消不为默认联系操作禁止
  const index = form.contacts.findIndex(fe => fe.type === 1);
  if (index === -1) {
    e.type = 1
    ElMessage.warning("当前已是默认联系人")
  } else {
    // 循环将选中的移除
    form.contacts.forEach(fe => {
      if (fe.index === e.index)
        return
      fe.type = 0
    })
  }
}
//添加标签画像
const addPortrait = () => {
  form.portraitLabels.push('')
}
//添加联系人
const addContact = () => {
    form.contacts.push({
    index: form.contacts.length + 1, // 往前推
    name: '',
    phone: null,
    wechat: null,
    type: 1,
    postiton: null,
    roleName: null
  })
}
//删除联系人
const delContact = (e) => {form.contacts.splice(e, 1)}
//删除供应产品选项
const delOfferOption = (row,e) => {
  console.log(row)
  if (row.id == null || row.id == undefined || row.id ==''){
    //否则...
  }else {
    delProductRecord({id: row.id}).then(res => {
      if (res.data) {
        offerProductOption.value.splice(e, 1)
        ElMessage.success("删除成功!")
      }
    })
  }
}
//删除标签画像
const delPortrait = (e) => {form.portraitLabels.splice(e, 1)}
//提交
const submit = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (!valid) return // 必填没有填就直接结束
    try {
      // console.log(state.form);
      // 如果为空不检查
      // 有填入就校验
      // 检查联系人手机号是否正确
      form.contacts.forEach((f, index) => {
        if (f.phone || f.phone !== '') {
          const testMobileValue = /^[1][3,4,5,6.7,8,9][0-9]{9}$/
          if (!testMobileValue.test(f.phone))
            throw new Error("联系人" + (index + 1) + "的手机号不正确，请输入正确的手机号");
        }
      })
      form.addrName = addrName.value //转化实际地址
      for (let i = 0; i < form.contacts.length; i++) {
        if(form.contacts[i].type == 1){
          form.mainContact = form.contacts[i] //主要联系人
          break;
        }
      }


      //处理请求数据
      var formData = new FormData()
      fileList.value.forEach((file) => {
        formData.append('fileList', file.raw)
      })
      formData.append('supplierImg',supplierImg.value)
      const json = JSON.stringify(form)
      const blob = new Blob([json], {
        type: 'application/json'
      })
      formData.append('form',blob)
      //需要图片和参数一起发送则 使用formData
      // supplierApi.create(formData).then(res => {
      //   if (res){
      //     ElMessage.success("成功");
      //   }
      // })

      //不需要合并发送 只使用form参数
      supplierApi.create(form).then(res => {
        if (res.data){
          ElMessage.success("成功");
          // 调用父组件刷新列表
          emit('onSubmit', true)
          // 刷新抽屉状态
          emit("update:dialogDrawer", false)
          drawer = false
          form = {
            socialCode:'',
            name:'', // 全称
            shortName:'', //简称
            productName:'', //产品名称
            purchaseUserId:'',//采购人用户ID
            stage:'',
            state:'',
            areaDetail:[],
            createTime:'',
            contacts: [{index:0,name: '', phone: '', wechat: 0, type: 1, position: '',roleName:''}], //联系人列表
            mainContact :{name: '', phone: '', wechat: 0, type: 1, position: '',roleName:''},  //主要联系人
            portraitLabels:[{portraitLabel:''}], //用户画像 暂时无功能
            source:'2', //默认为2 其他
            address: null,  // 地址全称
            addrCode: null,   // 省市区地址编码, 逗号隔开
            addrName: null,   // 省市区地址, 逗号隔开
            lng: null,    // 经度
            lat: null,    // 纬度
            remark:''
          }
        }
      })
    } catch (e) {
      ElMessage.error(e.message);
    }
  })
}
const cancel = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  emit("update:dialogDrawer", false)
}
</script>

<style scoped>
.footer-fixed {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  padding: 10px;
  background: #fff;
  z-index: 999;
  display: flex;
  justify-content: center;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 0px 5px 0px, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px;
}
.auto{
  margin-left: 20px;
  margin-right: 30px;
  margin-top: 110px;
}

</style>

<style scoped lang="scss">
.drawer-form {
  padding: 10px 10px 64px;

  .upload-demo {
    width: 89.8%;

    :deep(.el-upload-dragger) {
      padding: 5px 0;
    }

    :deep(.el-upload__text) {
      margin-top: -15px;
    }
  }

  :deep(.el-form-item) {
    align-items: flex-start;
  }

  .row-item {
    // margin-bottom: 10px;
    :deep(.el-form-item:nth-child(2) .el-input__wrapper) {
      width: 116px;
    }
  }

  .remark-item {
    :deep(.el-textarea__inner) {
      width: 430px;
    }
  }

  #map {
    width: 89.8%;
    height: 150px;
    margin-top: 10px;
  }
}
</style>
